package com.qf.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.qf.domain.Address;
import com.qf.domain.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.Base64Util;
import com.qf.util.RandomUtil;
import com.qf.util.StringUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {
    //用户注册
    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1`获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //2`校验
        if(StringUtil.isEmpty(username)){
            request.setAttribute("msg","用户名不能为空");
            return "/register.jsp";
        }
        if(StringUtil.isEmpty(password)){
            request.setAttribute("msg","用户名不能为空");
            return "/register.jsp";
        }
        if(!password.equals(repassword)){//password取反
            request.setAttribute("msg","两次密码不一致");
            return "/register.jsp";
        }
        if(StringUtil.isEmpty(email)){
            request.setAttribute("msg","邮箱不能为空");
            return "/register.jsp";
        }
        //3`检验用户是否存在
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {
            request.setAttribute("msg","用户名已存在");
            return "/register.jsp";
        }
        //4`添加数据
        User user = new User(0,username,password,email,gender,0,1, RandomUtil.createActiveCode());
        try {
            userService.regist(user);
            return "registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","注册失败");
            return "/register.jsp";
        }

    }
    //添加验证码
    public String code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        //1创建验证码对象
        ValidateCode validateCode = new ValidateCode(100,38,4,10);
        //2把验证码放入session中
        request.getSession().setAttribute("vcode",validateCode.getCode());
        System.out.println("验证码是:"+validateCode.getCode());
        //3返回给浏览器
        validateCode.write(response.getOutputStream());//写入一个字节流
        return null;
    }
    //用户登录
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        String auto = request.getParameter("auto");//自动登录
        //校验
        if(StringUtil.isEmpty(username)){
            request.setAttribute("msg","用户不能为空");
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(password)){
            request.setAttribute("msg","密码不能为空");
            return "/message.jsp";
        }
        if(StringUtil.isEmpty(vcode)){
            request.setAttribute("msg","验证码能为空");
            return "/message.jsp";
        }
        //验证验证码是否正确
       String code = (String) request.getSession().getAttribute("vcode");
        if(!vcode.equalsIgnoreCase(code)){//对vcode取反 equalsIgnoreCase忽略大小写
            request.setAttribute("msg","验证码错误");
            return "/message.jsp";
        }
        //调到业务逻辑
        UserService userService = new UserServiceImpl();
        try {
            User user = userService.login(username,password);
            //存储用户
            request.getSession().setAttribute("user",user);

            //自动登录
            System.out.println(auto);
            if (auto != null) {
                //创建cookie
                String userinfo = username+"#"+password;
                //base64处理
                userinfo= Base64Util.encode(userinfo);
                Cookie cookie = new Cookie("userinfo",userinfo);
                //设置有效路径
                cookie.setPath(request.getContextPath());
                //有效日期
                cookie.setMaxAge(60*60*24*7);
                //设置httponly
                cookie.setHttpOnly(true);
                //回写
                response.addCookie(cookie);
            }
            //重定向
            if(user.getRole()==0){
                response.sendRedirect("/XiaoMi/admin/admin.jsp");
            }
            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg",e.getMessage());
            return "/login.jsp";
        }
    }
    //验证用户是否存在
    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("username"+username);
        if(StringUtil.isEmpty(username)){
            response.getWriter().write("1");//用户名不可用
            return null;
        }
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {//true存在
            response.getWriter().write("1");//进行回写
            return null;
        }
            response.getWriter().write("0");
        return null;
    }
    //退出登录
    public String loginOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //把session中的信息删除
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //session失效
        session.invalidate();//注销session
        //删除自动登录的cookie
        Cookie cookie = new Cookie("userinfo","");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //重定向
        return "redirect:/index.jsp";
    }
    //添加地址
    public String addAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "/redirct:/login.jsp";
        }
        //接受数据
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //验证
        if(StringUtil.isEmpty(name)){
            request.setAttribute("msg","用户名不能为空");
            return "/address_info.jsp";
        }
        if(StringUtil.isEmpty(phone)){
            request.setAttribute("msg","电话号码不能为空");
            return "/address_info.jsp";
        }
        if(StringUtil.isEmpty(detail)){
            request.setAttribute("msg","详细地址不能为空");
            return "/address_info.jsp";
        }
        try {
            //创建业务对象
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(0,detail,name,phone,user.getId(),0);
            addressService.add(address);
            //转发
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","添加失败");
            return "/address_info.jsp";
        }
    }
    //添加购物车
    public String getAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "/redirct:/login.jsp";
        }
        //创建业务对象
        try {
            AddressService addressService = new AddressServiceImpl();
            List<Address> addList = addressService.find(user.getId());
            request.setAttribute("addList",addList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/address_info.jsp";
        }
    //删除地址
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "/redirct:/login.jsp";
        }
        //获取前端数据
        String id = request.getParameter("id");
        //创建业务对象
        AddressService addressService = new AddressServiceImpl();
        try {
            addressService.remove(user.getId(),Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","删除地址失败");
            return "/address_info.jsp";
        }

    }
    //设置默认地址
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "/redirct:/login.jsp";
        }
        //获取前端数据
        String id = request.getParameter("id");
        //创建业务对象
        AddressService addressService = new AddressServiceImpl();
        try {
            addressService.updateLevel(user.getId(),Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","设置默认地址失败");
            return "/address_info.jsp";
        }

    }
    //修改地址
    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //判断是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "/redirct:/login.jsp";
        }
        //获取前端数据
        String aid = request.getParameter("id");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        String level = request.getParameter("level");
        //验证
        if(StringUtil.isEmpty(aid)){
            request.setAttribute("msg","地址编号不能为空");
            return "/address_info.jsp";
        }
        if(StringUtil.isEmpty(name)){
            request.setAttribute("msg","姓名不能为空");
            return "/address_info.jsp";
        }
        if(StringUtil.isEmpty(phone)){
            request.setAttribute("msg","电话号码不能为空");
            return "/address_info.jsp";
        }
        if(StringUtil.isEmpty(detail)){
            request.setAttribute("msg","地址不能为空");
            return "/address_info.jsp";
        }

        //创建业务对象
        AddressService addressService = new AddressServiceImpl();
        try {
            Address address = new Address(Integer.parseInt(aid),detail,name,phone,user.getId(),Integer.parseInt(level));
            addressService.update(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","设置默认地址失败");
            return "/address_info.jsp";
        }

    }

}

